<template>
  <base-layout>
    <div class="problem-container">
      <!-- 左侧题目区域 -->
      <div class="problem-description">
        <a-card class="description-card">
          <template #title>
            <div class="card-title">
              <span class="problem-id">#{{ problemId }}</span>
              <span class="problem-name">{{ problem.title }}</span>
              <a-tag :color="getDifficultyColor(problem.difficulty)">
                {{ problem.difficulty }}
              </a-tag>
            </div>
          </template>
          <div class="description-content">
            <div class="section">
              <h3>题目描述</h3>
              <div v-html="problem.description"></div>
            </div>
            <div class="section">
              <h3>输入描述</h3>
              <div v-html="problem.inputDesc"></div>
            </div>
            <div class="section">
              <h3>输出描述</h3>
              <div v-html="problem.outputDesc"></div>
            </div>
            <div class="section">
              <h3>示例</h3>
              <div v-for="(example, index) in problem.examples" :key="index" class="example">
                <div class="example-item">
                  <div class="example-title">输入示例 {{ index + 1 }}：</div>
                  <pre class="example-content">{{ example.input }}</pre>
                </div>
                <div class="example-item">
                  <div class="example-title">输出示例 {{ index + 1 }}：</div>
                  <pre class="example-content">{{ example.output }}</pre>
                </div>
                <div class="example-explanation" v-if="example.explanation">
                  <div class="example-title">解释：</div>
                  <div>{{ example.explanation }}</div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>

      <!-- 右侧代码编辑区域 -->
      <div class="code-editor">
        <a-card class="editor-card">
          <template #title>
            <div class="editor-header">
              <a-select v-model:value="selectedLanguage" style="width: 120px">
                <a-select-option value="java">Java</a-select-option>
                <a-select-option value="python">Python</a-select-option>
                <a-select-option value="cpp">C++</a-select-option>
              </a-select>
              <div class="editor-actions">
                <a-button @click="handleReset">
                  <template #icon><redo-outlined /></template>
                  重置
                </a-button>
                <a-button @click="handleSave">
                  <template #icon><save-outlined /></template>
                  保存
                </a-button>
                <a-button type="primary" :loading="submitting" @click="handleSubmit">
                  <template #icon><check-outlined /></template>
                  提交
                </a-button>
              </div>
            </div>
          </template>
          <div class="editor-container">
            <textarea
              ref="codeEditor"
              v-model="code"
              class="code-textarea"
              @keydown.tab.prevent="handleTab"
              @paste.prevent
              @copy.prevent
              @cut.prevent
              @contextmenu.prevent
              spellcheck="false"
              autocomplete="off"
            ></textarea>
          </div>
        </a-card>

        <!-- 提交结果 -->
        <a-card class="result-card">
          <template #title>
            <div class="result-header">
              <span>提交结果</span>
              <a-tag v-if="showResult" :color="getStatusTag(submissionResult.status).color">
                {{ getStatusTag(submissionResult.status).text }}
              </a-tag>
              <a-tag v-else color="default">未提交</a-tag>
            </div>
          </template>
          <div class="result-content">
            <div v-if="showResult">
              <div class="result-item">
                <span class="label">执行用时：</span>
                <span class="value">{{ submissionResult.executionTime }}</span>
              </div>
              <div class="result-item">
                <span class="label">内存消耗：</span>
                <span class="value">{{ submissionResult.memoryUsage }}</span>
              </div>
              <div v-if="submissionResult.error" class="error-message">
                {{ submissionResult.error }}
              </div>
              <div class="result-files">
                <h4>提交详情</h4>
                <div class="file-list">
                  <div class="file-item" v-for="file in submissionResult.files" :key="file.id">
                    <div class="file-info">
                      <file-text-outlined />
                      <span class="file-name">{{ file.name }}</span>
                      <span class="file-size">{{ formatFileSize(file.size) }}</span>
                    </div>
                    <div class="file-actions">
                      <a-button type="link" @click="handlePreview(file)">
                        <template #icon><eye-outlined /></template>
                        预览
                      </a-button>
                      <a-button type="link" @click="handleDownload(file)">
                        <template #icon><download-outlined /></template>
                        下载
                      </a-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-result">
              <div class="empty-text">暂无提交记录</div>
            </div>
          </div>
        </a-card>
      </div>
    </div>
  </base-layout>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { 
  CheckOutlined, 
  RedoOutlined, 
  SaveOutlined,
  FileTextOutlined,
  EyeOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'
import { ojApi } from '@/api'

export default {
  name: 'OJProblem',
  components: {
    BaseLayout,
    CheckOutlined,
    RedoOutlined,
    SaveOutlined,
    FileTextOutlined,
    EyeOutlined,
    DownloadOutlined
  },
  setup() {
    const route = useRoute()
    const problemId = ref(route.params.id)
    const selectedLanguage = ref('java')
    const code = ref('')
    const submitting = ref(false)
    const showResult = ref(false)
    const codeEditor = ref(null)

    // 模拟题目数据
    const problem = ref({
      title: '两数之和',
      difficulty: '简单',
      description: `给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。\n\n你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。\n\n你可以按任意顺序返回答案。`,
      inputDesc: '- nums：一个整数数组，长度在 [2, 104] 范围内\n- target：一个整数，取值范围在 [-109, 109] 内',
      outputDesc: '返回一个长度为2的整数数组，表示符合条件的两个数的下标',
      examples: [
        {
          input: 'nums = [2,7,11,15], target = 9',
          output: '[0,1]',
          explanation: '因为 nums[0] + nums[1] == 9，返回 [0, 1]'
        },
        {
          input: 'nums = [3,2,4], target = 6',
          output: '[1,2]',
          explanation: '因为 nums[1] + nums[2] == 6，返回 [1, 2]'
        }
      ]
    })

    // 模拟提交结果
    const submissionResult = ref({
      id: Date.now(),
      status: Math.random() > 0.5 ? 'passed' : 'failed',
      executionTime: '156ms',
      memoryUsage: '12.5MB',
      score: Math.random() > 0.5 ? 100 : 60,
      submitTime: new Date().toLocaleString(),
      language: selectedLanguage.value,
      testcases: [
        {
          input: 'arr = [3, 1, 4, 1, 5, 9, 2, 6]',
          expectedOutput: '[1, 1, 2, 3, 4, 5, 6, 9]',
          actualOutput: '[1, 1, 2, 3, 4, 5, 6, 9]',
          status: 'passed',
          executionTime: '52ms',
          memoryUsage: '4.2MB'
        },
        {
          input: 'arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]',
          expectedOutput: '[1, 2, 3, 4, 5, 6, 7, 8, 9]',
          actualOutput: '[1, 2, 3, 4, 5, 6, 7, 8, 9]',
          status: 'passed',
          executionTime: '48ms',
          memoryUsage: '4.1MB'
        },
        {
          input: 'arr = [1]',
          expectedOutput: '[1]',
          actualOutput: '[2]',
          status: 'failed',
          executionTime: '45ms',
          memoryUsage: '4.0MB'
        }
      ],
      files: [
        {
          name: `提交详情报告_${Date.now()}.txt`,
          type: 'report',
          size: 1024 * 512,
          url: `report_${Date.now()}`
        },
        {
          name: `测试用例结果_${Date.now()}.txt`,
          type: 'testcases',
          size: 1024 * 512,
          url: `testcases_${Date.now()}`
        }
      ]
    })

    const handleTab = (e) => {
      const start = e.target.selectionStart
      const end = e.target.selectionEnd
      const value = e.target.value
      e.target.value = value.substring(0, start) + '    ' + value.substring(end)
      e.target.selectionStart = e.target.selectionEnd = start + 4
    }

    const handleSubmit = async () => {
      if (!code.value.trim()) {
        message.error('请输入代码')
        return
      }

      submitting.value = true
      try {
        // 模拟提交响应
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 模拟提交结果数据
        submissionResult.value = {
          id: Date.now(),
          status: Math.random() > 0.5 ? 'passed' : 'failed',
          executionTime: '156ms',
          memoryUsage: '12.5MB',
          score: Math.random() > 0.5 ? 100 : 60,
          submitTime: new Date().toLocaleString(),
          language: selectedLanguage.value,
          testcases: [
            {
              input: 'arr = [3, 1, 4, 1, 5, 9, 2, 6]',
              expectedOutput: '[1, 1, 2, 3, 4, 5, 6, 9]',
              actualOutput: '[1, 1, 2, 3, 4, 5, 6, 9]',
              status: 'passed',
              executionTime: '52ms',
              memoryUsage: '4.2MB'
            },
            {
              input: 'arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]',
              expectedOutput: '[1, 2, 3, 4, 5, 6, 7, 8, 9]',
              actualOutput: '[1, 2, 3, 4, 5, 6, 7, 8, 9]',
              status: 'passed',
              executionTime: '48ms',
              memoryUsage: '4.1MB'
            },
            {
              input: 'arr = [1]',
              expectedOutput: '[1]',
              actualOutput: '[2]',
              status: 'failed',
              executionTime: '45ms',
              memoryUsage: '4.0MB'
            }
          ],
          files: [
            {
              name: `提交详情报告_${Date.now()}.txt`,
              type: 'report',
              size: 1024 * 512,
              url: `report_${Date.now()}`
            },
            {
              name: `测试用例结果_${Date.now()}.txt`,
              type: 'testcases',
              size: 1024 * 512,
              url: `testcases_${Date.now()}`
            }
          ]
        }
        showResult.value = true
        message.success('提交成功')
      } catch (error) {
        message.error('提交失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 保存代码到 localStorage
    const handleSave = () => {
      const key = `oj_problem_${problemId.value}_${selectedLanguage.value}`
      localStorage.setItem(key, code.value)
      message.success('代码已保存')
    }

    // 加载历史代码
    const loadSavedCode = () => {
      const key = `oj_problem_${problemId.value}_${selectedLanguage.value}`
      const savedCode = localStorage.getItem(key)
      if (savedCode) {
        code.value = savedCode
        message.info('已加载上次保存的代码')
      } else {
        // 如果没有保存的代码，使用模板
        const templates = {
          java: `class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 在这里写入你的代码
        return new int[]{0, 0};
    }
}`,
          python: `class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        // 在这里写入你的代码
        return [0, 0]`,
          cpp: `class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 在这里写入你的代码
        return {0, 0};
    }
};`
        }
        code.value = templates[selectedLanguage.value]
      }
    }

    // 监听语言变化
    watch(selectedLanguage, () => {
      loadSavedCode()
    })

    // 重置时清除本地存储
    const handleReset = () => {
      const key = `oj_problem_${problemId.value}_${selectedLanguage.value}`
      localStorage.removeItem(key)
      code.value = ''
      showResult.value = false
      loadSavedCode() // 重置为模板代码
      message.info('代码已重置')
    }

    const getDifficultyColor = (difficulty) => {
      const colors = {
        '简单': 'success',
        '中等': 'warning',
        '困难': 'error'
      }
      return colors[difficulty] || 'default'
    }

    const getStatusTag = (status) => {
      switch (status) {
        case 'passed':
          return { color: 'success', text: '通过' }
        case 'failed':
          return { color: 'error', text: '未通过' }
        default:
          return { color: 'default', text: status }
      }
    }

    // 处理文件预览
    const handlePreview = async (file) => {
      try {
        const mockData = file.type === 'report' 
          ? `提交详情报告
===================

提交时间：${new Date().toLocaleString()}
语言：${selectedLanguage.value}
执行结果：${submissionResult.value.status === 'passed' ? '通过' : '未通过'}
得分：${submissionResult.value.score}
执行用时：${submissionResult.value.executionTime}
内存消耗：${submissionResult.value.memoryUsage}

代码分析
-------------------
1. 时间复杂度：O(n)
2. 空间复杂度：O(n)
3. 代码质量：良好
4. 改进建议：可以考虑使用哈希表优化查找效率

测试用例执行情况
-------------------
通过用例数：2
失败用例数：1
通过率：66.67%

详细测试用例结果请查看测试用例文件`
          : `测试用例执行结果：

============= 测试用例 1 =============
输入：
arr = [3, 1, 4, 1, 5, 9, 2, 6]

预期输出：
[1, 1, 2, 3, 4, 5, 6, 9]

实际输出：
[1, 1, 2, 3, 4, 5, 6, 9]

执行时间：52ms
内存使用：4.2MB
状态：通过

============= 测试用例 2 =============
输入：
arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]

预期输出：
[1, 2, 3, 4, 5, 6, 7, 8, 9]

实际输出：
[1, 2, 3, 4, 5, 6, 7, 8, 9]

执行时间：48ms
内存使用：4.1MB
状态：通过

============= 测试用例 3 =============
输入：
arr = [1]

预期输出：
[1]

实际输出：
[2]

执行时间：45ms
内存使用：4.0MB
状态：未通过`

        const blob = new Blob([mockData], {
          type: 'text/plain;charset=utf-8'
        })
        
        const reader = new FileReader()
        reader.onload = (e) => {
          const win = window.open('', '_blank')
          win.document.write(`
            <html>
              <head>
                <title>${file.name}</title>
                <style>
                  body {
                    font-family: monospace;
                    white-space: pre;
                    padding: 20px;
                    background: #f5f5f5;
                    line-height: 1.5;
                  }
                </style>
              </head>
              <body>${e.target.result}</body>
            </html>
          `)
        }
        reader.readAsText(blob, 'utf-8')
        
        message.success('预览已打开')
      } catch (error) {
        message.error('预览失败：' + (error.message || '未知错误'))
      }
    }

    // 处理文件下载
    const handleDownload = async (file) => {
      try {
        // 模拟API响应数据
        const mockData = file.type === 'report' 
          ? `%PDF-1.4
1 0 obj
<< /Type /Catalog
   /Pages 2 0 R
>>
endobj

2 0 obj
<< /Type /Pages
   /Kids [3 0 R]
   /Count 1
>>
endobj

3 0 obj
<< /Type /Page
   /Parent 2 0 R
   /Resources << /Font << /F1 4 0 R >> >>
   /MediaBox [0 0 612 792]
   /Contents 5 0 R
>>
endobj

4 0 obj
<< /Type /Font
   /Subtype /Type1
   /BaseFont /Helvetica
>>
endobj

5 0 obj
<< /Length 68 >>
stream
BT
/F1 12 Tf
72 720 Td
(提交详情报告) Tj
(代码分析和执行结果概述) Tj
ET
endstream
endobj

xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000233 00000 n
0000000301 00000 n
trailer
<< /Size 6
   /Root 1 0 R
>>
startxref
421
%%EOF`
          : `测试用例执行结果：

============= 测试用例 1 =============
输入：
arr = [3, 1, 4, 1, 5, 9, 2, 6]

预期输出：
[1, 1, 2, 3, 4, 5, 6, 9]

实际输出：
[1, 1, 2, 3, 4, 5, 6, 9]

执行时间：52ms
内存使用：4.2MB
状态：通过

============= 测试用例 2 =============
输入：
arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]

预期输出：
[1, 2, 3, 4, 5, 6, 7, 8, 9]

实际输出：
[1, 2, 3, 4, 5, 6, 7, 8, 9]

执行时间：48ms
内存使用：4.1MB
状态：通过

============= 测试用例 3 =============
输入：
arr = [1]

预期输出：
[1]

实际输出：
[2]

执行时间：45ms
内存使用：4.0MB
状态：未通过`

        // 创建 Blob 对象，设置正确的 MIME 类型和编码
        const blob = new Blob([mockData], {
          type: file.type === 'report' 
            ? 'application/pdf' 
            : 'text/plain;charset=utf-8'
        })
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = file.name
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        message.success('下载成功')
      } catch (error) {
        message.error('下载失败：' + (error.message || '未知错误'))
      }
    }

    // 格式化文件大小
    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / 1024 / 1024).toFixed(2) + ' MB'
      }
    }

    onMounted(() => {
      loadSavedCode()
    })

    return {
      problemId,
      problem,
      selectedLanguage,
      code,
      submitting,
      showResult,
      submissionResult,
      codeEditor,
      handleTab,
      handleSubmit,
      handleReset,
      handleSave,
      getDifficultyColor,
      getStatusTag,
      formatFileSize,
      handlePreview,
      handleDownload
    }
  }
}
</script>

<style scoped>
.problem-container {
  display: flex;
  gap: 24px;
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.problem-description {
  flex: 1;
  min-width: 0;
  max-width: 50%;
  display: flex;
  flex-direction: column;
}

.code-editor {
  flex: 1;
  min-width: 0;
  max-width: 50%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.description-card,
.editor-card,
.result-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.problem-id {
  color: #8c8c8c;
  font-weight: normal;
}

.problem-name {
  font-weight: 500;
  font-size: 16px;
}

.description-content {
  font-size: 14px;
  line-height: 1.6;
  flex: 1;
  overflow-y: auto;
  height: calc(100vh - 140px);
  min-height: 700px;
  padding: 16px;
}

.section {
  margin-bottom: 24px;
}

.section h3 {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 500;
}

.example {
  margin-bottom: 16px;
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.example-item {
  margin-bottom: 8px;
}

.example-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.example-content {
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
  margin: 0;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.editor-actions .ant-btn {
  display: flex;
  align-items: center;
}

.editor-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200px);
  min-height: 600px;
}

.code-textarea {
  width: 100%;
  height: 100%;
  padding: 12px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: none;
  tab-size: 4;
  flex: 1;
  margin: 16px;
  margin-top: 0;
}

.code-textarea:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: none;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-content {
  font-size: 14px;
}

.result-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.result-item .label {
  color: #8c8c8c;
  margin-right: 8px;
}

.error-message {
  margin-top: 12px;
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  color: #ff4d4f;
}

.empty-result {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px;
}

.empty-text {
  color: #8c8c8c;
  font-size: 14px;
}

.result-files {
  margin-top: 16px;
}

.file-list {
  margin-top: 8px;
}

.file-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name {
  font-weight: 500;
}

.file-size {
  color: #8c8c8c;
  font-weight: normal;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .ant-btn {
  display: flex;
  align-items: center;
}

@media screen and (max-width: 1200px) {
  .problem-container {
    flex-direction: column;
  }

  .problem-description,
  .code-editor {
    max-width: none;
  }

  .description-card,
  .editor-card {
    height: auto;
  }

  .editor-container,
  .description-content {
    height: 700px;
    min-height: auto;
  }
}

.error-output {
  color: #ff4d4f;
  font-weight: 500;
}
</style> 